package io.github.yotta.logger.core.aop;


import io.github.yotta.logger.anno.annotation.LogOperation;
import io.github.yotta.logger.core.support.LogMetaDataDiscover;
import org.springframework.aop.ClassFilter;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.core.annotation.AnnotationUtils;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author yotta
 * @date 2023/3/21 17:25
 */
@SuppressWarnings("all")
public class LogPointcut extends StaticMethodMatcherPointcut implements ClassFilter {

    private final LogMetaDataDiscover logMetaDataDiscover;

    public LogPointcut(LogMetaDataDiscover logMetaDataDiscover) {
        this.logMetaDataDiscover = logMetaDataDiscover;
    }


    @Override
    public ClassFilter getClassFilter() {
        return this;
    }

    @Override
    public boolean matches(Class<?> clazz) {
        String className = clazz.getName();
        return !this.exclude(className);
    }

    /**
     * 去掉那些被代理的类
     *
     * @param name
     * @return
     */
    private boolean exclude(String name) {
        if (name.startsWith("java")) {
            return true;
        } else if (name.startsWith("org.springframework")) {
            return true;
        } else if (name.indexOf("$$EnhancerBySpringCGLIB$$") >= 0) {
            return true;
        } else {
            return name.indexOf("$$FastClassBySpringCGLIB$$") >= 0;
        }
    }


    /**
     * 匹配加了LogOperation注解的bean
     */
    @Override
    public boolean matches(Method method, Class<?> targetClass) {
        final boolean isMatch = matchImpl(method, targetClass);
        if (isMatch) {
            // 提前收集日志操作的元数据信息
            logMetaDataDiscover.discover(method, targetClass);
        }
        return isMatch;
    }

    private boolean matchImpl(Method method, Class<?> targetClass) {
        final LogOperation annotation = AnnotationUtils.findAnnotation(method, LogOperation.class);
        if (Objects.isNull(annotation)) {
            return false;
        }
        return true;
    }
}
